package controller

import (
	"encoding/json"
	"github.com/e421083458/go_gateway_demo/dao"
	"github.com/e421083458/go_gateway_demo/dto"
	"github.com/e421083458/go_gateway_demo/middleware"
	"github.com/e421083458/go_gateway_demo/public"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"time"
)

type AdminController struct {
	
}

func AdminRegister(group *gin.RouterGroup) {
	admin := &AdminController{}
	group.POST("/login", admin.login)
	group.GET("/logout", admin.logout)
}

// AdminLogin godoc
// @Summary 管理员登录
// @Description 管理员登录
// @Tags 管理员接口
// @ID /admin/login
// @Accept  json
// @Produce  json
// @Param body body dto.AdminInput true "body"
// @Success 200 {object} middleware.Response{data=dto.AdminOutput} "success"
// @Router /admin/login [post]
func (admin *AdminController) login(c *gin.Context)  {
	params := &dto.AdminInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 10001, err)
		return
	}

	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 20001, err)
		return
	}
	adminM := &dao.Admin{}
	adminM, err = adminM.LoginCheck(c, tx, params)
	if err != nil {
		middleware.ResponseError(c, 20002, err)
		return
	}

	// 设置 session
	sessionInfo := &dto.AdminSessionInfo{
		ID: adminM.Id,
		UserName: adminM.UserName,
		LoginTime: time.Now(),
	}
	sessBts, err := json.Marshal(sessionInfo)
	if err != nil {
		middleware.ResponseError(c, 20003, err)
		return
	}
	sess := sessions.Default(c)
	sess.Set(public.AdminSessionInfoKey, string(sessBts))
	sess.Save()

	out := &dto.AdminOutput{Token: adminM.UserName}
	middleware.ResponseSuccess(c, out)
}

// AdminLogout godoc
// @Summary 管理员退出
// @Description 管理员退出
// @Tags 管理员接口
// @ID /admin/logout
// @Accept  json
// @Produce  json
// @Success 200 {object} middleware.Response{data=string} "success"
// @Router /admin/logout [get]
func (admin *AdminController) logout(c *gin.Context)  {
	sess := sessions.Default(c)
	sess.Delete(public.AdminSessionInfoKey)
	sess.Save()

	middleware.ResponseSuccess(c, "")
}
